object special methods


In [1]:
import sys
sys.version


Out[1]:
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'

In [2]:
from builtins import object

In [2]:
object??

In [3]:
# Py3-style iterators written as new-style classes (subclasses of
# future.builtins.object) are backward compatibile with Py2:
class Upper(object):
    def __init__(self, iterable):
        self._iter = iter(iterable)
    def __next__(self):                 # note the Py3 interface
        return next(self._iter).upper()
    def __iter__(self):
        return self

In [5]:
assert list(Upper('hello')) == list('HELLO')

In [6]:
class AllOrNothing(object):
    def __init__(self, l):
        self.l = l
    def __bool__(self):
        return all(self.l)

In [8]:
container = AllOrNothing([0, 100, 200])
bool(container)


Out[8]:
False

In [9]:
container2 = AllOrNothing([-100, 100, 200])
bool(container2)


Out[9]:
True

Classes derived from Python builtins don't have this behaviour:


In [13]:
class AllOrNothingBroken(list):
    def __bool__(self):
        print('Called!')
        return all(self)

In [14]:
container3 = AllOrNothingBroken([0, 1, 2])
bool(container3)


Out[14]:
True

But subclasses of future types do:


In [15]:
from builtins import list

class AllOrNothingFixed(list):
    def __bool__(self):
        print('Called!')
        return all(self)

In [17]:
container4 = AllOrNothingFixed([0, 1, 2])
bool(container4)


Out[17]:
True

In [ ]: